package com.stone.sys.action;

/**
 * 变电站
 * <pre>
 * @author：JZ
 * @since:2010/02/10
 * </pre>
 */
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;

import com.stone.common.pojo.TFile;
import com.stone.para.IConstant;
import com.stone.sys.pojo.TBdz;
import com.stone.sys.pojo.TBdzJg;
import com.stone.sys.pojo.TUser;
import com.stone.sys.service.SysCommonService;
import com.stone.utils.DateFormatTool;
import com.stone.utils.FileUtils;
import com.stone.utils.JsonUtils;
import com.stone.utils.StringUtils;

import frm.ssh.action.BaseListAction;
import frm.ssh.exception.AppException;

public class BdzAction extends BaseListAction {
	
	public HashMap<String, Object> setSearchCondition() {
		return null;
	}

	private static final long serialVersionUID = 865527685459140622L;

	private SysCommonService myService;
	
	// 变电站于修改
	private TBdz entity;

	// 间隔实体用于修改
	private TBdzJg entityJg;
	
//	// 屏柜实体用于修改
//	private TBdzPg entityPg;
	
	private String id;
	private String bdzid;
	private List<TFile> attachList;
	private String filename;
	private File uploadFile;
	private String uploadFileFileName;
	private String fileid;
	private String pageFrom;
	private String kzkid;
	/**
	 * 查询列表
	 */	
	public void getBdzList() throws IOException, AppException {
		
		HashMap<String, Object> m = new HashMap<String, Object>();
		List<Object> valsList = new ArrayList<Object>();
		
		// 状态
		String conditions = "dic.itemId = bdz.dydj";
		
		// 变电站名称
		if(!StringUtils.isNullOrBlankFull(super.getSearchBean().getCon3())) {
			conditions += " and bdz.bdzname like ?";
			valsList.add("%" + super.getSearchBean().getCon3() + "%");
		}
		
		// 电压等级
		if (!StringUtils.isNullOrBlankFull(super.getSearchBean().getCon2())) {
			conditions += " AND bdz.dydj = ?";
			valsList.add(super.getSearchBean().getCon2());
		}

		List<HashMap<String, Object>> list = myService.getListByDHql("bdz.tyrq as tyrq, bdz.cs as cs,bdz.dz as dz, bdz.dydj as dydj, bdz.sortid as sortid, bdz.remark as remark, bdz.id as id, bdz.bdzcode as bdzcode, bdz.bdzname as bdzname, dic.itemName as dydjname", 
				conditions , valsList.toArray(), "order by bdz.sortid", "TBdz bdz, TDictionary dic");
		
        JsonConfig jsonConfig = JsonUtils.configJson(new String[] {}, "yyyy-MM-dd");
    	
        JSON json = JSONSerializer.toJSON(list, jsonConfig);

		String strjson = "{result:" + json.toString() + ",totalCount:[" + list.size() + "]}";
		
        super.getResponse().getWriter().print(strjson);
		
	}
	
	/**
	 * 保存变电站
	 */	
	public void save() throws IOException, AppException {
		
		long count = 0;
		
		String out = "{rep:true,success:true,msg:'变电站编号重复',id:'" + entity.getId() + "'}";
		
		// 新建
		if (entity.getId() == 0) {
			
			count = myService.getTotalByDHql("bdzcode = ?", new Object[]{entity.getBdzcode()}, "TBdz");
			
			if (count > 0) {
		        super.getResponse().getWriter().print(out);
		        return;
			}
			
			myService.save(entity);

			// 修改
		} else {
			
			count = myService.getTotalByDHql("bdzcode = ? and id != ? ", new Object[]{entity.getBdzcode(), entity.getId()}, "TBdz");
			
			if (count > 0) {
		        super.getResponse().getWriter().print(out);
		        return;
			}
			
			myService.update(entity);
		}
		
		// 修改排序号
		if(entity.getSortid() == null || entity.getSortid() == 0) {
			myService.updateByHQL("update TBdz set sortid = ? where id = ?",new Object[] { entity.getId(), entity.getId()});
		}

		super.getResponse().getWriter().print("{success:true,msg:'保存成功',id:'" + entity.getId() + "'}");
		
	}
	
	/**
	 * 删除
	 * @return
	 * @throws AppException
	 */
	public void delete() throws Exception {
		
		myService.doDelAll(id, TBdz.class.getName());
		
		super.getResponse().getWriter().print("删除成功");
		
	}

	/**
	 * 间隔、屏柜维护时左侧变电站树
	 */	
	@SuppressWarnings("unchecked")
	public void getBdzTree() throws IOException, AppException {
		
		String parentid = super.getRequest().getParameter("parentid");

		List<HashMap<String, Object>> list = null;
		
		if ("0".equals(parentid)) {
		
			list = myService.getListByDHql(
					" t.dydj || 'kv'  as id, dic.itemName as text, 0 as leaf,dic.sortid", 
					"t.dydj = dic.itemId and dic.itemType = 'DYDJ'", 
					null, 
					" group by t.dydj,  dic.itemName,dic.sortid order by dic.sortid", 
					" TBdz t, TDictionary dic ");
		} else {
			
			list = myService.getListByDHql(
					" t.id as id, t.bdzname as text, 1 as leaf", 
					" t.dydj = ? ", 
					new Object[] {parentid.replace("kv", "")}, 
					" order by t.sortid", 
					" TBdz t");
			
		}

        JsonConfig jsonConfig = JsonUtils.configJson(new String[] {}, "yyyy-MM-dd");
    	
        JSON json = JSONSerializer.toJSON(list, jsonConfig);

        super.getResponse().getWriter().print(json.toString());
		
	}

	/**
	 * 查询间隔、屏柜列表
	 */	
	@SuppressWarnings("unchecked")
	public void getBdzJgList() throws IOException, AppException {

		List<HashMap<String, Object>> list = myService.getListByDHql(
				" jg.id as id, jg.bdzid as bdzid, jg.jgbh as jgbh, jg.jgmc as jgmc, jg.dydj as dydj, dic1.itemName as dydjname, jg.jglx as jglx, dic2.itemName as jglxname,jg.tyrq as tyrq", 
				" jg.state = '" + super.getSearchBean().getCon1() + "' and jg.dydj = dic1.itemId and dic1.itemType = 'DYDJ' and jg.jglx = dic2.itemId and dic2.itemType = '" + super.getSearchBean().getCon2() + "' and bdzid = ? " , 
				new Object[]{id}, 
				"", 
				"TBdzJg jg, TDictionary dic1, TDictionary dic2");
		
        JsonConfig jsonConfig = JsonUtils.configJson(new String[] {}, "yyyy-MM-dd");
    	
        JSON json = JSONSerializer.toJSON(list, jsonConfig);

		String strjson = "{result:" + json.toString() + ",totalCount:[" + list.size() + "]}";
		
        super.getResponse().getWriter().print(strjson);
		
	}

	/**
	 * 保存间隔、屏柜
	 */	
	public void saveJg() throws IOException, AppException {
		
		long count = 0;
		
		String out = "{rep:true,success:true,msg:'间隔编号重复',id:'" + entityJg.getId() + "'}";
		
		if ("2".equals(super.getSearchBean().getCon1())) {
			out = "{rep:true,success:true,msg:'屏柜编号重复',id:'" + entityJg.getId() + "'}";
		}
		
		// 新建
		if (entityJg.getId() == 0) {
			
			count = myService.getTotalByDHql("state = ? and jgbh = ? and bdzid = ? ", new Object[]{super.getSearchBean().getCon1(), entityJg.getJgbh(),entityJg.getBdzid()}, "TBdzJg");
			
		if (count > 0) {
		        super.getResponse().getWriter().print(out);
		        return;
			}
			
			myService.save(entityJg);

			// 修改
		} else {
			
			count = myService.getTotalByDHql("state = ? and jgbh = ? and id != ? and bdzid = ? ", new Object[]{super.getSearchBean().getCon1(), entityJg.getJgbh(), entityJg.getId(),entityJg.getBdzid()}, "TBdzJg");
			
			if (count > 0) {
		        super.getResponse().getWriter().print(out);
		        return;
			}
			
			myService.update(entityJg);
		}
		
		super.getResponse().getWriter().print("{success:true,msg:'保存成功',id:'" + entityJg.getId() + "'}");
		
	}
	
	/**
	 * 删除间隔、屏柜
	 * @return
	 * @throws AppException
	 */
	public void deleteJg() throws Exception {
		
		myService.doDelAll(id, TBdzJg.class.getName());
		
		super.getResponse().getWriter().print("删除成功");
		
	}
/**
	 * 弹出变电站树
	 */	
	@SuppressWarnings("unchecked")
	public void getBdzTreePopup() throws IOException, AppException {

		List<HashMap<String, Object>> list1 = null;

		// 获得电压等级
		list1 = myService.getListByDHql(
					"t.dydj || 'kv'  as id, dic.itemName as text, 'root' as parentId, '000' as qtip", 
					"t.dydj = dic.itemId and dic.itemType = 'DYDJ'", 
					null, 
					" group by t.dydj,  dic.itemName,dic.sortid order by dic.sortid", 
					" TBdz t, TDictionary dic ");

		List<HashMap<String, Object>> list2 = myService.getListByDHql(
					" t.id as id, t.bdzname as text, t.dydj || 'kv' as parentId, '000000000' as qtip ", 
					"", 
					null,
					" order by t.sortid", 
					" TBdz t");
		list1.addAll(list2);
        JsonConfig jsonConfig = JsonUtils.configJson(new String[] {}, "yyyy-MM-dd");
    	
        JSON json = JSONSerializer.toJSON(list1, jsonConfig);

        super.getResponse().getWriter().print(json.toString());
		
	}
	public String getBdz(){
		return "BDZ_SUCCESS";
	}
	public String getBdzjg(){
		return "BDZJG_SUCCESS";
	}
	public String getBdzpg(){
		return "BDZPG_SUCCESS";
	}
	public String getBzgsk(){
		return "BZGSK_SUCCESS";
	}
	public String getSbtz(){
		return "SBTZ_SUCCESS";
	}
//	/**
//	 * 查询屏柜列表
//	 */	
//	@SuppressWarnings("unchecked")
//	public void getBdzPgList() throws IOException, AppException {
//		
//		List<HashMap<String, Object>> list = myService.getListByDHql(
//				" jg.id as id, jg.bdzid as bdzid, jg.pgbh as pgbh, jg.pgmc as pgmc, jg.dydj as dydj, dic1.itemName as dydjname, jg.pglx as pglx, dic2.itemName as pglxname,jg.tyrq as tyrq", 
//				" jg.dydj = dic1.itemId and dic1.itemType = 'DYDJ' and jg.pglx = dic2.itemId and dic2.itemType = 'PGLX' and bdzid = ? " , 
//				new Object[]{id}, 
//				"", 
//				"TBdzPg jg, TDictionary dic1, TDictionary dic2");
//		
//        JsonConfig jsonConfig = JsonUtils.configJson(new String[] {}, "yyyy-MM-dd");
//    	
//        JSON json = JSONSerializer.toJSON(list, jsonConfig);
//
//		String strjson = "{result:" + json.toString() + ",totalCount:[" + list.size() + "]}";
//		
//        super.getResponse().getWriter().print(strjson);
//		
//	}

//	/**
//	 * 保存屏柜
//	 */	
//	public void savePg() throws IOException, AppException {
//		
//		long count = 0;
//		
//		String out = "{rep:true,success:true,msg:'屏柜编号重复',id:'" + entityPg.getId() + "'}";
//		
//		// 新建
//		if (entityPg.getId() == 0) {
//			
//			count = myService.getTotalByDHql("pgbh = ?", new Object[]{entityPg.getPgbh()}, "TBdzPg");
//			
//			if (count > 0) {
//		        super.getResponse().getWriter().print(out);
//		        return;
//			}
//			
//			myService.save(entityPg);
//
//			// 修改
//		} else {
//			
//			count = myService.getTotalByDHql("pgbh = ? and id != ? ", new Object[]{entityPg.getPgbh(), entityPg.getId()}, "TBdzPg");
//			
//			if (count > 0) {
//		        super.getResponse().getWriter().print(out);
//		        return;
//			}
//			
//			myService.update(entityPg);
//		}
//		
//		super.getResponse().getWriter().print("{success:true,msg:'保存成功',id:'" + entityPg.getId() + "'}");
//		
//	}
//	
//	/**
//	 * 删除屏柜
//	 * @return
//	 * @throws AppException
//	 */
	public void deletePg() throws Exception {
		
		//myService.doDelAll(id, TBdzPg.class.getName());
		//myService.doDelAll(id);
		myService.deleteEquip(id);
		super.getResponse().getWriter().print("删除成功");
	
	}
/**
	 * 屏柜维护时左侧变电站树
	 */	
	@SuppressWarnings("unchecked")
	public void getBdzJgTree() throws IOException, AppException {
		
		String parentid = super.getRequest().getParameter("parentid");
		// 电压等级
		List<HashMap<String, Object>> list = null;
		
		if ("0".equals(parentid)) {
		
			list = myService.getListByDHql(
					" t.dydj || 'kv'  as id, dic.itemName as text, 0 as leaf,dic.sortid,'' as qtip", 
					"t.dydj = dic.itemId and dic.itemType = 'DYDJ'", 
					null, 
					" group by t.dydj,  dic.itemName,dic.sortid order by dic.sortid", 
					" TBdz t, TDictionary dic ");
			// 变电站
		} else if (parentid.endsWith("kv")) {
			
			list = myService.getListByDHql(
					" t.id as id, t.bdzname as text, 0 as leaf,'' as qtip", 
					" t.dydj = ? ", 
					new Object[] {parentid.replace("kv", "")}, 
					" order by t.sortid", 
					" TBdz t");
			// 间隔
		} else {
			list = myService.getListByDHql(
					" t.id as id, t.jgmc||t.jgbh as text, 1 as leaf,'间隔' as qtip", 
					" t.state = '1' and t.bdzid = ? ", 
					new Object[] {Long.parseLong(parentid)}, 
					" order by t.id", 
					" TBdzJg t");
		}

        JsonConfig jsonConfig = JsonUtils.configJson(new String[] {}, "yyyy-MM-dd");
    	
        JSON json = JSONSerializer.toJSON(list, jsonConfig);

        super.getResponse().getWriter().print(json.toString());
		
	}
	/**
	 * 查询间隔、屏柜列表
	 */	
	@SuppressWarnings("unchecked")
	public void getBdzPgList() throws IOException, AppException {

		List<HashMap<String, Object>> list = myService.getListByDHql(
				" jg.id as id, jg.bdzid as bdzid, jg.jgbh as jgbh, jg.jgmc as jgmc, jg.dydj as dydj, dic1.itemName as dydjname, jg.jglx as jglx, dic2.itemName as jglxname,jg.tyrq as tyrq,jg.parentid as parentid", 
				" jg.state = '2' and jg.dydj = dic1.itemId and dic1.itemType = 'DYDJ' and jg.jglx = dic2.itemId and dic2.itemType = '" + super.getSearchBean().getCon2() + "' and parentid = ? " , 
				new Object[]{id}, 
				"", 
				"TBdzJg jg, TDictionary dic1, TDictionary dic2");
		
        JsonConfig jsonConfig = JsonUtils.configJson(new String[] {}, "yyyy-MM-dd");
    	
        JSON json = JSONSerializer.toJSON(list, jsonConfig);

		String strjson = "{result:" + json.toString() + ",totalCount:[" + list.size() + "]}";
		
        super.getResponse().getWriter().print(strjson);
		
	}
	
	public TBdz getEntity() {
		return entity;
	}

	public void setEntity(TBdz entity) {
		this.entity = entity;
	}

	public void setMyService(SysCommonService myService) {
		this.myService = myService;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public TBdzJg getEntityJg() {
		return entityJg;
	}

	public void setEntityJg(TBdzJg entityJg) {
		this.entityJg = entityJg;
	}

	public String getBdzid() {
		return bdzid;
	}

	public void setBdzid(String bdzid) {
		this.bdzid = bdzid;
	}

	public List<TFile> getAttachList() {
		return attachList;
	}

	public void setAttachList(List<TFile> attachList) {
		this.attachList = attachList;
	}
	
	@SuppressWarnings("unchecked")
	public String getBdzAttachment() throws AppException {
		attachList = myService.findListByHql("from TFile where tableid = '" + id + "' AND colname = 'TAB_BDZ_ATTACHMENT'");
		
		if("workcard".equals(pageFrom))
			return "CHOOSE_BDZ_ATTACH";
		else
			return "ATTACH_SUCCESS";
	}

	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	public File getUploadFile() {
		return uploadFile;
	}

	public void setUploadFile(File uploadFile) {
		this.uploadFile = uploadFile;
	}

	public String getUploadFileFileName() {
		return uploadFileFileName;
	}

	public void setUploadFileFileName(String uploadFileFileName) {
		this.uploadFileFileName = uploadFileFileName;
	}
	
	public String uploadBdzFile() throws AppException {
		if (uploadFile != null
				&& (uploadFile.length() > IConstant.FILE_BUFFER_SIZE
						* IConstant.FILE_SIZE_TEN * IConstant.FILE_SIZE_HUNDRED)) {
			super.setInfo("上传失败，附件不能超过10M");// OUTOFSIZE
			return SUCCESS;
		}
		TFile tFile = null;
		if (uploadFile != null) {
			System.out.println("==========" + uploadFileFileName);
			String filePath = super.getRealPath() + "upload/bdz_files";

			File upDir = new File(filePath);
			if (!upDir.exists()) {
				upDir.mkdirs();
			}

			String saveFileName = UUID.randomUUID().toString()
					+ FileUtils.getExtention(uploadFileFileName);
			File saveFile = new File(filePath + "\\" + saveFileName);
			// 上传文件
			try {
				org.apache.commons.io.FileUtils.copyFile(uploadFile, saveFile);
				tFile = new TFile();
				tFile.setUrl("/DLPLANMIS/upload/bdz_files/" + saveFileName);
				if (this.filename == null || "".equals(this.filename))
					tFile.setFilename(uploadFileFileName);
				else
					tFile.setFilename(this.filename);
				tFile.setRealfilename(saveFileName);

				tFile.setTableid(Long.parseLong(this.getId()));
				tFile.setColname("TAB_BDZ_ATTACHMENT");
				tFile.setOperuser(((TUser) super.getSession().getAttribute(
						IConstant.SESSION_TUSER)).getId());
				tFile.setOperdate(DateFormatTool.formatToDate(myService
						.getSysdate("yyyy-MM-dd HH24:mi"), true));
				tFile.setImageflag("1");

			} catch (IOException e) {
				e.printStackTrace();
				super.setInfo("文件上传出现错误");
				throw new AppException("上传失败");
			}
		}
		myService.save(tFile);
		getBdzAttachment();
		return "ATTACH_SUCCESS";
	}
	
	public void attachDelete() throws AppException{
		TFile entity = (TFile) myService.findById(Long
				.parseLong(this.fileid), TFile.class.getName());

		// 删除文件
		String filePath = super.getRealPath() + "upload/bdz_files";
		File f = new File(filePath + "\\"  + entity.getRealfilename());
		
		if (f.exists()) {
			f.delete();
		}

		// 删除数据库
		this.myService.delete(fileid, "TFile");
	}

	public String getFileid() {
		return fileid;
	}

	public void setFileid(String fileid) {
		this.fileid = fileid;
	}

	public String getPageFrom() {
		return pageFrom;
	}

	public void setPageFrom(String pageFrom) {
		this.pageFrom = pageFrom;
	}

	public String getKzkid() {
		return kzkid;
	}

	public void setKzkid(String kzkid) {
		this.kzkid = kzkid;
	}

//	public TBdzPg getEntityPg() {
//		return entityPg;
//	}
//
//	public void setEntityPg(TBdzPg entityPg) {
//		this.entityPg = entityPg;
//	}
//	
	

}
